const app = getApp();
/**
 * 获取字符串转换json
 **/
module.exports.getJson = function (val) {
  return this.isEmpty(val) ? {} : JSON.parse(val);
}

/**
 * 判断数否为空  验证完成
 * @param {type} v 任意数
 * @return {bool} 返回true为空值
 */
module.exports.isEmpty = function (v) {
  if (v === undefined || v === null || v === '' || v === 'undefined' || v === 'null') return true;
  if (typeof v === 'object' && v.constructor === Array && v.length === 0) return true;
  if (typeof v === 'object'){
		var jsonLength=0;
		for(var k in v){
			jsonLength++;
		}
		if(jsonLength==0) return true;
  }
  return false;
}

/*
* 是否是数组
 * @param n  任意字符
 * return bool  验证完成
*/
module.exports.isArray = function (n) {
  return Array.isArray(n);
}

/**
 * 接收过滤参数
 * @param str 接收的值
 * @param s   如果为空，使用默认值
 */
module.exports._get = function (str,s) {
  var _this = this;
  if(_this.isEmpty(str)&&!_this.isEmpty(s)) return s;
  if(_this.isEmpty(str)) return '';
  return str;
}

/**
 * 过滤空值
 * @param {type} str 字符串或数组
 * @return
 */
module.exports._str = function (str) {
	var com = this;
	if(com.isEmpty(str)){
		if(str==null || str == undefined || str =='') return '';
		if(typeof str == 'object'){
		  return str.constructor == Array?[]:{};
		}else{
		  return "";
		}
	}
	if (typeof str == 'object') {
		if(str.constructor == Array){
		  for(var i = 0;i<str.length;i++){
			str[i] = com._str(str[i]);
		  }
		}else{
		  for (var k in str) {
			  str[k] = com._str(str[k]);
		  }
		}
		return str;
	} else {
		return com.isEmpty(str)?'':str;
	}
}
/*
 * 整数数字  验证完成
 */
module.exports.int = function (s) {
  if (s == '' || s == undefined || s == null || isNaN(parseInt(s)) == true) {
    return 0;
  }
  return parseInt(s);
}

/**
 * 跳转
 * @param u 地址
 * @param t 类型
 * @param j  参数  验证完成
 */
module.exports.toUrl = function (u,j = {},t='_blank') {
  var c = this,it='',g = app.globalData;
  let pages = getCurrentPages();
  let currPage = null;
  if (c.isEmpty(u)||c.isEmpty(t)) uni.navigateBack({});
  for (var item in j) {
    it = it == '' ? '?' + item + '=' + j[item] : it + '&' + item + '=' + j[item];
  }
  u = c.indexList(u,'/')?u:'pages/' + u + '/' + u,
  t = c.indexList(g.tabBar,u)?'_tab':t,
  u = '/' + u + it;
  console.log('跳转地址',u);
  if(t == '_blank') uni.navigateTo({url:u});
  if(t == '_self') uni.redirectTo({url: u});
  if(t == '_tab') uni.switchTab({url: u});
  if(t == '_close') uni.reLaunch({url: u});
}

/**
 * 拨打电话
 * @param s 电话  验证完成
 */
module.exports.call = function (s) {
  uni.makePhoneCall({
    phoneNumber: s
  });
}

/**
 * 打开地图  验证完成
 */
module.exports.toMap = function(j){
  if(this.isEmpty(j.latitude)) return false;
  uni.openLocation({
    latitude: Number(j.latitude),
    longitude: Number(j.longitude),
    address: j.address,
    name: j.name,
    scale: 18
  });
}

/*
 * 图片上传
 * param f 执行方法
 * t 选择类型
 * dir 存储目录
 */
module.exports.chooseImage = function (json = {},f) {
  var com = this;
  json.t = com.isEmpty(json.t)?1:json.t;
  json.dir = com.isEmpty(json.dir) ? 'couponimage' : json.dir,
  json.count = com.isEmpty(json.dir)?1:json.count;
  // json.count = 9;
  json.sourceType = com.isEmpty(json.sourceType) ? ['album', 'camera'] : json.sourceType;
  json.sizeType = com.isEmpty(json.sizeType) ? ['original', 'compressed'] : json.sizeType
  switch (json.t) {
    case 2:
      json.sourceType = ['album'];
    case 3:
      json.sourceType = ['camera'];
    default:
      json.sourceType = ['album', 'camera'];
  }
  uni.chooseImage({
    count: json.count, // 默认9
    sizeType: json.sizeType, // 可以指定是原图还是压缩图，默认二者都有
    sourceType: json.sourceType,
    success: function (res) {
	    uni.showLoading({
		  icon: 'loading',
		  title:'正在上传'
		});
      var tempFilePaths = res.tempFilePaths;
	  let fileList = []
	 //  for(let i in tempFilePaths){
		// fileList.push({name:'file',url:tempFilePaths[i]})
	 //  }
	  for(let i in tempFilePaths){
			com.uploadFile({
				path: tempFilePaths[i],
				dir: json.dir
			},f);
		}
		uni.hideLoading();
    },fail() {
    	uni.hideLoading();
    }
  })
},
/*
*上传
*/
module.exports.uploadFile = function (json,f) {
	uni.uploadFile({
	  url:app.globalData.host + 'upload/uploadFile',
	  filePath: json.path,
	  name: 'file',
	  // files:json.path,
	  header: {
		"content-type": "multipart/form-data"
	  },
	  formData: {
		filename:"file",
	  },
	  success: function (res) {
		f(res,json.path);
	  }, fail: function (res) {
		console.log('错误', res);
	  }
	})
},
module.exports.uploadPan = function (json,i,f) {
	console.log('fffffff',i)
	uni.uploadFile({
	  url:app.globalData.host + 'upload/uploadPan',
	  filePath: json.path,
	  name: 'file',
	  // files:json.path,
	  header: {
		"content-type": "multipart/form-data"
	  },
	  formData: {
		filename:"file",
		token:app.globalData.token,
		pid:i.pid,
		classinfo_id:i.classinfo_id,
		type:i.type,
		file:i.file
	  },
	  success: function (res) {
		f(res,json.path);
	  }, fail: function (res) {
		console.log('错误', res);
	  }
	})
},
// 预览
module.exports.previewImage = function (e,p) {
	var com = this;
	var pis = com.isEmpty(p)?[e]:p
    uni.previewImage({
      current: e,
      urls: pis
    })
},

/**
 * 保存图片
 * @param u 图片地址
 * @param f 处理方法
 */
module.exports.save = function (u,f = function(){}){
  var c = this;
  uni.showLoading({
    icon: 'loading',
    title:'正在保存...'
  });
  uni.downloadFile({
    url: u,
    success: function (e) {
		uni.hideLoading();
		uni.saveImageToPhotosAlbum({
			filePath: e.tempFilePath,
			success(e) {
				c.toAlert('保存成功!');
				if(typeof f === 'funciton') f(e);
			},
			fail:function (err) {
				uni.showModal({
					title: '温馨提示',
					content: '您好，需要您的授权',
					showCancel: false,
					success:modalSuccess=>{
					  uni.openSetting({
						success(settingdata) {
							if (settingdata.authSetting['scope.writePhotosAlbum']) {
								c.save(u,f);
							} else {
								uni.showModal({
								  title: '温馨提示',
								  content: '您好，获取权限失败！',
								  showCancel: false,
								});
							}
						},
						fail(failData) {
							console.log("failData",failData)
						},
						complete(finishData) {
							console.log("finishData", finishData)
						}
					  });
					}
				});
			}
		});
    },fail: function(res) {
		uni.hideLoading();
        uni.showModal({
          title: '下载失败',
          content: '请联系管理员',
        });
      },
      complete: function(res) {},
	});
}

/**
 * 无图片提示  验证完成
 * */
module.exports.toAlert = function (title, t) {
  if (t == undefined) t = 3000;
  uni.showToast({
    title: title,
	icon: "none",
    duration: t
  });
}

/**
 * 成功提示  验证完成
**/
module.exports.toAst = function (title, t) {
  var c = this,t = c.isEmpty(t)?3000:t;
  uni.showToast({
    title: title,
    icon: 'success',
    duration: t
  });
}

/**
 * 提示确认  验证完成
 * */
module.exports.modal = function (title, content, f = function(){}) {
  uni.showModal({
    title: title,
    content: content,
    success: function (e) {
      if (e.confirm) {
        f(e);
      } else if (e.cancel) {

      }
    }
  })
}

/**
 * 多个json数据合并 最多3个 验证完成
 */
module.exports.allJson = function (){
  var c = this,arr = [];
  for(var i=0;i<arguments.length;i++){
	  if(!c.isEmpty(arguments[i]))
	  arr.push(arguments[i]);
  }
  var j = c.isEmpty(arr)?{}:arr[0];
  for(var i = 1;i<arr.length;i++){
    var _j = arr[i];
    for (var item in _j) {
        j[item] = c._str(_j[item]);
    }
  }
  return j;
}

/**
 * 设置/返回  app.globalData
 * @param n  字符串/对象
 * @param json 对象
 * return 字符/对象  验证完成
 */
module.exports.g = function (n,j) {
  var c = this,g = app.globalData;
  if(c.isEmpty(n)) return g;
  if (typeof n === 'object') {
	for (var i in n) {
	  g[i] = n[i];
	}
  } else {
	if (typeof n === 'string' && typeof j === 'object') {
	  if (c.isEmpty(g[n])) g[n] = {};
	  for (var i in j) {
		g[n][i] = j[i];
	  }
	}
  }
  if(c.isEmpty(n)) return g;
  return g[n];
}

/**
 * 获取表单或是节点的值 验证完成
 * @return {object}
*/
module.exports.data = function (e,n) {
  var c = this;
  if(c.isEmpty(n)&&e.type === 'tap'){
	  var j = e.currentTarget.dataset;
	  delete j.eventOpts;
	  return j;
  }
  if(!c.isEmpty(n)&&e.detail.source=='autoplay') return  e.detail[n];
  if(e.type === 'submit' || e.type == 'blur' || e.type == 'change' || e.type == 'input' || e.type =='confirm'){
	return c._get(c.isEmpty(n)?e.detail.value:e.detail.target.dataset[n]);
  }
  if(c.isEmpty(n)&&e.type == 'click'){
	  return e.currentTarget.dataset;
  }
  return e.currentTarget.dataset[n];
}

/**
 * 判断数据集中是否包含，指定json条件的中，t不为空为部分包含，默认为全包含
 * @param list 数据集
 * @param j 判断条件
 * @return 所在的序号
 */
module.exports.indexList = function (list,j,t) {
	var c = this,r=[];
	if(c.isEmpty(list)||c.isEmpty(j)) return false;
	//数组包含 json 数据条件
	if(typeof list === 'object' && typeof j === 'object'){
		for(var i=0;i<list.length;i++){
		  var a='',b='',ri=false;
		  for (var key in j) {
			a = a + key+list[i][key];
			b = b + key+j[key];
			ri = list[i][key] == j[key]?true:ri;
		  }
		  //部分包含
		  if(!c.isEmpty(t)){
			r = !c.isEmpty(t)&&ri==true&&c.indexList(i,r)==false?c._push(i,r) : r;
		  }else{
			r = !c.isEmpty(a)&&a==b?c._push(i,r) : r;
		  }
		}
	}
	//字符串 是否 在数组中
	if(list.constructor === Array && typeof j === 'string'){
		for(var i=0;i<list.length;i++){
		  r = list[i].indexOf(j)!=-1?c._push(i,r) : r;
		}
	}
	//字符串包含
	if(typeof list === 'string'&&typeof j === 'string'){
		r = list.split(j);
		r = r.length==1?false:r;
	}
	return c.isEmpty(r)?false:r;
}

/**
 * 验证
 * t = {type:mobile,key:name,err:'错误'}
 * j = {name:'张三'}  验证完成
 */
module.exports.verify = function (t,j) {
	var c = this,t = c.isEmpty(t)?'empty':t;
	var v = {
		empty:function(s){
			return !c.isEmpty(s);
		},
		email : /^(\w-*\.*)+@(\w-?)+(\.\w{2,})+$/,
		mobile : /^(1[0-9])[0-9]{9}$/,
		int : /(^[\-0-9][0-9]*(.[0-9]+)?)$/,
		idcard :/(^[1-9]\d{5}(18|19|([23]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$)|(^[1-9]\d{5}\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{2}$)/,
		tel : /^(\+\d{2}-)?0\d{2,3}-\d{7,8}$/,
		price : function(s){
		  if(s == "0" || s == "0." || s == "0.0" || s == "0.00"){
			return true;
		  }else{
			if(s.indexOf("0") === 0 && s.length > 1){///*0开头的数字串*/
				return (/^[0]{1}[.]{1}[0-9]{1,2}$/).test(s) ? true : false;
			}else{
				return (/^[1-9]{1}[0-9]{0,10}[.]{0,1}[0-9]{0,2}$/).test(s)? true :false;
			}
			return false;
		  }
		}
	}
	//单值验证
	if(typeof t === 'string' && typeof j === 'string'){
		for(var k in v){
			if(k === t){
				return typeof v[k] === 'function'?v[k](j) : (v[k].test(j)?true:false);
			}
		}
	}
	//复合值验证
	if(typeof t === 'object' && typeof j === 'object'){
		for (var i in t) {
			for (var k in j){
				if (t[i].key === k){
					if((!c.isEmpty(j[k])&&!c.isEmpty(t[i].empty))||c.isEmpty(t[i].empty)){
						if(typeof v[t[i].type] === 'string'||typeof v[t[i].type] === 'object'){
							if(!(v[t[i].type]).test(j[k])){
								if(!c.isEmpty(t[i].err)){
									c.toAlert(t[i].err);
								}
								return false;
							}
						}else{
							if(!((v[t[i].type])(j[k]))){
								if(!c.isEmpty(t[i].err)){
									c.toAlert(t[i].err);
								}
								return false;
							}
						}
					}
				}
			}
		}
	}
	return true;
}

/**
 * 设置标题  验证完成
 */
module.exports.setTitle = function (j) {
  if (typeof j == 'object') {
    uni.setNavigationBarTitle(j);
  } else {
    uni.setNavigationBarTitle({
      title: j
    });
  }
}
// 日期时间戳转换
module.exports.timeToDate = function(time,format){ // time 可以是时间戳 可以是Y-m-d H:i:s
	if (time === undefined) {
	  return '';
	}
	if (format === undefined) {
	  format = 'Y-m-d H:i:s';
	}
	var date = new Date(time*1000); //
	var Y = date.getFullYear();
	var m = (date.getMonth()+1 < 10 ? '0'+(date.getMonth()+1) : date.getMonth()+1) ;
	var d = date.getDate() < 10 ? '0'+date.getDate()+'' : date.getDate();
	var H = date.getHours() < 10 ? '0'+date.getHours()+'' : date.getHours();
	var i = date.getMinutes() < 10 ? '0'+date.getMinutes()+'' : date.getMinutes();
	var s = date.getSeconds() < 10 ? '0'+date.getSeconds() : date.getSeconds();
	var timestr = '';
	format = format.replace("Y",Y).replace("m",m).replace("d",d).replace("H",H).replace("i",i).replace("s",s);
	return format;
}

/**
 * 无提示 ajax
*/
module.exports.toAjax = function (u, j, m,f = function(){}) {
	var c  = this;
	console.log('app.globalData',app.globalData)
    if(c.isEmpty(app.globalData.token)){
        uni.login({
        	provider: 'weixin',
        	success: res => {
        		// 发送 res.code 到后台换取 openId, sessionKey, unionId
        		if (res.code) {
        		  	//发起网络请求 logincode
        		  	uni.request({
        				url: app.globalData.host+'login/login',
        				data: app.getParamet({
        					code: res.code,
          					v: app.globalData.SDKVersion,
          					model: app.globalData.model
        				}),
        				success: function (resa) {
        					if (resa.data.code == 1) {
        						var result = resa.data.info;
        						app.globalData.phone = result.phone;
        						app.globalData.originally.phone = result.phone;
        						app.globalData.userid = result.userid;
        						app.globalData.originally.userid = result.userid;
        						app.globalData.token = result.token;
        						app.globalData.originally.token = result.token;
        						app.globalData.session_key = result.session_key;
        						app.globalData.ishas = result.ishas;
        						app.globalData.userInfo = result.userinfo;
        					}
                            uni.request({
                            	url: app.globalData.host + u,
                            	method: m,
                            	data: c.sign(j),
                            	header: {
                            	  'content-type': 'application/x-www-form-urlencoded' //默认值
                            	},
                            	success: function (e) {
                            		f(e);
                            	},
                            	fail: function (e) {
                            		c.modal("检测到网络失败","确认重新加载",function (){
                            			this.onShow();
                            		});
                            	}
                            });
        				}
        		  	})
        		}
        	}
        })
    }else{
        uni.request({
        	url: app.globalData.host + u,
        	method: m,
        	data: c.sign(j),
        	header: {
        	  'content-type': 'application/x-www-form-urlencoded' //默认值
        	},
        	success: function (e) {
        		f(e);
        	},
        	fail: function (e) {
        		c.modal("检测到网络失败","确认重新加载",function (){
        			this.onShow();
        		});
        	}
        });
    }
	
}

/**
 * 有提示 ajax
*/
module.exports.toAjaxT = function (u, j, m,f = function(){}) {
	uni.showLoading({
	    title: '加载中',
	});
	var c  = this;
	uni.request({
		url: app.globalData.host + u,
		method: m,
		data: c.sign(j),
		header: {
		  'content-type': 'application/x-www-form-urlencoded' //默认值
		},
		success: function (e) {
			wx.hideLoading();
			f(e);
		},
		fail: function (e) {
			wx.hideLoading();
			c.modal("检测到网络失败","确认重新加载",function (){
				this.onShow();
			});
		}
	});
}

/*
* 签名
*/
module.exports.sign = function (j = {}) {
	var c = this,s = '',g = app.globalData;
	j.token = g.token;
	//过滤
	j = c._str(j);
	var data = j;
	return data;
}

/**
/*刷新当前页
*/
module.exports._show = function () {
	this.onShow();
}

// 图片地址

module.exports.imgsrc = function () {
	var src = 'https://school.zhxqpt.cn'
	return src;
}

/**
/*刷新当前页
*/
module.exports._show = function () {
	this.onShow();
}


module.exports.getUserInfo = function (e,f = function(){}) {
  var $s = this,u = '/cardindex/index';
  uni.showLoading({title:'正在登录...'});
  if (e.detail.errMsg == "getUserInfo:ok") {
	var j = e.detail.userInfo;
		j.tlitpic = j.avatarUrl;
	$s.toAjax(u,j,'post',function (e){
	  uni.hideLoading();
	  var r = e.data;
	  if (r.bol) {
		var userInfo = r.data.userinfo;
		$s.g({userInfo:userInfo});
		$s.toAlert('登录成功！');
		f(r);
	  }
	});
  }else{
	uni.hideLoading();
  }
}

/* *
 * 获取用户手机号
**/
module.exports.getPhone = function (e,f=function(){}) {
  var $s = this;
  if (e.detail.errMsg == "getPhoneNumber:ok") {
	var encryptedData = e.detail.encryptedData;
	var iv = e.detail.iv;
	uni.login({
	  success: function (e) {
		if (e.code) {
		  var url = "/usercard/get_user_phone";
		  $s.toAjax(url, {
			code: e.code,
			iv: iv,
			encryptedData: encryptedData
		  }, 'post',function (e) {
			var r = e.data;
			if (r.bol==true) {
			  var phone = r.data.phone;
			  $s.userInfo['phone'] = phone;
			  f(phone);
			}else{
				$s.toAlert(e.errMsg);
			}
		  });
		} else {
		  console.log('获取用户登录态失败！' + e.errMsg)
		}
	  },
	  complete: function () {
	  }
	});
  }
}

module.exports.formatNumber = n => {
  n = n.toString()
  return n[1] ? n : '0' + n
}
module.exports.formatDate = str => {
  var _this = this
  const year = str.getFullYear();
  const month = str.getMonth() + 1;
  const day = str.getDate();
  return [year, month].map(_this.formatNumber).join('-');
}
